﻿<div id="app" class="common-layout">
    <!-- 出库单据基础信息 -->
    <div class="basicInfo">
        <h4 class="titleH">基础信息</h4>
        <hr />
        <div class="form-container">
            <el-form :model="form" label-width="120px" class="basicInfoForm">
                <table class="orderTable">
                    <tbody>
                        <!-- 第一行：出库单号 + 出库类型 -->
                        <tr>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;出库单号
                            </td>
                            <td>
                                <el-input v-model="form.outboundOrderNo"
                                          placeholder="自动获取系统编号"
                                          style="width:70%;"
                                          readonly />
                            </td>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;出库类型
                            </td>
                            <td>
                                <el-select v-model="form.outboundType"
                                           placeholder="请选择"
                                           style="width:90%"
                                           v-on:change="handleOutboundTypeChange">
                                    <el-option v-for="item in outboundTypeOptions"
                                               :key="item.label"
                                               :label="item.value"
                                               :value="item.label">
                                    </el-option>
                                </el-select>
                            </td>
                        </tr>

                        <!-- 第二行：仓库名称 + 出库日期 -->
                        <tr>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;仓库名称
                            </td>
                            <td>
                                <el-select v-model="form.warehouseId"
                                           placeholder="请选择仓库"
                                           style="width:70%"
                                           v-on:change="handleWarehouseChange">
                                    <el-option v-for="item in warehouseOptions"
                                               :key="item.warehouseId"
                                               :label="item.warehouseName"
                                               :value="item.warehouseId">
                                    </el-option>
                                </el-select>
                            </td>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;出库日期
                            </td>
                            <td>
                                <el-date-picker v-model="form.outboundDate"
                                                type="date"
                                                format="YYYY/MM/DD"
                                                value-format="YYYY/MM/DD"
                                                placeholder="选择出库日期"
                                                :default-value="new Date()"
                                                style="width: 160px;"
                                                clearable="true" />
                            </td>
                        </tr>

                        <!-- 第三行：关联单号 + 客户名称 -->
                        <tr>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;关联单号
                            </td>
                            <td style="text-align: center;">
                                <div class="related-order-input-group">
                                    <el-input v-model="form.relatedOrderNo"
                                              placeholder="请选择"
                                              style="width:calc(70% - 40px)"
                                              :disabled="!isSalesOutbound"
                                              v-on:click="openRelatedOrderModal">
                                        ...
                                    </el-input>
                                    <el-checkbox v-model="isRelateOutboundOrder"
                                                 :disabled="!isSalesOutbound"
                                                 style="margin-left:8px;">
                                        关联出库单号
                                    </el-checkbox>
                                </div>
                            </td>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;客户名称
                            </td>
                            <td>
                                <el-input v-model="form.customerName"
                                          placeholder="请输入"
                                          style="width:90%"
                                          readonly />
                            </td>
                        </tr>

                        <!-- 第四行：收货人 + 联系方式 -->
                        <tr>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;收货人
                            </td>
                            <td>
                                <el-cascader v-model="form.consignee"
                                             class="formTableSelect"
                                             placeholder="请选择收货人"
                                             :options="consigneeOptions"
                                             :props="{ expandTrigger: 'hover', label: 'name', value: 'id', children: 'children' }"
                                             v-on:change="handleConsigneeChange"
                                             style="width:70%">
                                </el-cascader>
                            </td>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;联系方式
                            </td>
                            <td>
                                <el-input v-model="form.contactInfo"
                                          placeholder="请先选择收货人"
                                          style="width:90%"
                                          readonly />
                            </td>
                        </tr>

                        <!-- 第五行：经办人 -->
                        <tr>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;经办人
                            </td>
                            <td>
                                <el-input v-model="form.operatorName"
                                          placeholder="请选择经办人"
                                          readonly
                                          style="width:70%"
                                          v-on:click="openOperatorModal"></el-input>
                            </td>
                            <td></td>
                            <td></td>
                        </tr>

                        <!-- 第六行：备注 -->
                        <tr>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;备注
                            </td>
                            <td colspan="3">
                                <el-input v-model="form.remark"
                                          type="textarea"
                                          placeholder="请输入"
                                          style="width:100%" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </el-form>
        </div>
    </div>

    <!-- 出库货品明细 -->
    <div class="stockInfo">
        <h2 class="titleH">出库货品明细</h2>
        <hr />
        <div class="add-remove-buttons">
            <div class="addAndRemove">
                <el-button type="success" v-on:click="openGoodsSelectModal">添加</el-button>
                <el-button type="danger" v-on:click="removeSelectedDetails">移除选中</el-button>
            </div>
            <div class="stockTable">
                <el-table :data="outboundDetails" style="width: 100%" v-on:selection-change="handleDetailSelection"
                          ref="detailTable" stripe border>
                    <el-table-column fixed type="selection" width="50"></el-table-column>
                    <el-table-column fixed prop="goodsName" label="货品名称" width="180"></el-table-column>
                    <el-table-column fixed prop="goodsCode" label="货品编号" width="140"></el-table-column>
                    <el-table-column prop="goodsTypeName" label="货品类型" width="100"></el-table-column>
                    <el-table-column prop="specification" label="规格型号" width="80"></el-table-column>
                    <el-table-column prop="unit" label="单位" width="80">
                        <template #default="scope">
                            <!-- 关联销售订单时固定单位为"个" -->
                            <template v-if="isRelateOutboundOrder">
                                个
                            </template>
                            <template v-else>
                                {{ scope.row.unit || '个' }}
                            </template>
                        </template>
                    </el-table-column>


                    <!-- 销售数量列 -->
                    <el-table-column prop="salesQuantity" label="销售数量" width="100" :formatter="formatNumber" v-if="isRelateOutboundOrder"></el-table-column>

                    <!-- 已出库数量列 -->
                    <el-table-column prop="outboundQuantity" label="已出库数量" width="100" :formatter="formatNumber"></el-table-column>

                    <!-- 修改库位列为显示库位名称 -->
                    <el-table-column prop="storageLocationName" label="出库库位" width="130">
                        <template #default="scope">
                            <span>{{ scope.row.storageLocationName || '无库位信息' }}</span>
                        </template>
                    </el-table-column>

                    <!-- 未出库数量列 -->
                    <el-table-column prop="nonOutboundQuantity" label="未出库数量" width="100" :formatter="formatNumber"></el-table-column>

                    <!-- 出库数量列（仅非关联订单时显示） -->
                    <el-table-column prop="outboundQuantity" label="出库数量" width="100" v-if="!isRelateOutboundOrder">
                        <template #default="scope">
                            <el-input v-model.number="scope.row.outboundQuantity"
                                      style="width: 100%"
                                      v-on:input="handleOutboundQuantityInput(scope.row)"
                                      clearable></el-input>
                        </template>
                    </el-table-column>
                    <!-- 当前库存列 -->
                    <el-table-column prop="availableStock" label="当前库存" width="100" :formatter="formatNumber"></el-table-column>
                    <!-- 本次出库数量列 -->
                    <el-table-column prop="currentOutStockQty" label="本次出库数量" width="130">
                        <template #default="scope">
                            <el-input v-model.number="scope.row.currentOutStockQty"
                                      style="width: 100%"
                                      v-on:input="handleCurrentOutStockQtyInput(scope.row)"
                                      v-on:blur="validateOutStockQuantity(scope.row)"
                                      :class="{'input-error': scope.row.hasStockError}"
                                      clearable></el-input>
                            <div v-if="scope.row.hasStockError" style="color: #f56c6c; font-size: 12px; margin-top: 4px;">
                                出库数量不能大于库存
                            </div>
                        </template>
                    </el-table-column>

                    <!-- 出库单价列 -->
                    <el-table-column prop="outboundUnitPrice" label="出库单价(元)" width="110" :formatter="formatNumber"></el-table-column>
                    <el-table-column label="出库金额" width="90" :formatter="calculateOutboundAmount"></el-table-column>

                    <!-- 备注列 -->
                    <el-table-column prop="remarks" label="备注" width="200">
                        <template #default="scope">
                            <el-input v-model="scope.row.remarks" placeholder="请输入"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" min-width="100">
                        <template #default="scope">
                            <el-button class="operate-btn"
                                       link type="primary" size="default"
                                       v-on:click="removeDetail(scope.$index)"
                                       min-width="100">
                                移除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

            </div>
        </div>
        <!-- 合计行 -->
        <div class="total-summary">
            <span class="promptWord">合计</span>
            <div class="countNum" style="display:inline-block;margin-left:45%">
                <span class="promptWord">出库数量: <span class="valueV">{{ formatNumber(null, null, outboundTotalQuantity) }}</span></span>&nbsp;&nbsp;&nbsp;&nbsp;
                <span class="promptWord">出库金额: <span class="valueV">{{ formatNumber(null, null, totalAmount) }}</span>元</span>
            </div>
        </div>
    </div>

    <!-- 附件上传区域 -->
    <div class="uploadAttachment">
        <h4 class="titleH">上传附件</h4>
        <hr />
        <div class="uploadAttach">
            <div class="uploadBtn">
                <input type="file"
                       ref="fileInput"
                       v-on:change="handleFileUpload"
                       accept=".doc,.docx,.pdf,.rar,.zip"
                       multiple
                       style="display: none" />
                <el-button type="primary" v-on:click="triggerFileInput">上传附件</el-button>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <span class="promptWord">您可以上传doc、pdf、rar、zip等格式的文件，单个文件最大200MB</span>
            </div>
            <div class="attachment-list">
                <div v-for="(file, index) in uploadedFiles" :key="index" class="attachment-item">
                    <div class="attachment-info">
                        <el-icon class="attachment-icon">
                            <document />
                        </el-icon>
                        <span>{{ file.name }}</span>
                    </div>
                    <div class="attachment-actions">
                        <el-button size="small"
                                   type="text"
                                   style="color: #ff4d4f;"
                                   v-on:click="removeFile(index)">
                            删除
                        </el-button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 底部保存栏 -->
    <div class="saveBlock">
        <div class="btnBlock">
            <el-button v-on:click="closePage">关闭</el-button>
            &nbsp;&nbsp;&nbsp;&nbsp;<el-button v-on:click="saveDraft">保存草稿</el-button>
            &nbsp;&nbsp;&nbsp;&nbsp;<el-button v-on:click="saveAndAdd">保存并新增</el-button>
            &nbsp;&nbsp;&nbsp;&nbsp;<el-button type="success"
                                               v-on:click="submitForm"
                                               :disabled="submitting"
                                               :loading="submitting">
                {{ submitting ? '提交中...' : '提交订单' }}
            </el-button>
        </div>
    </div>

    <!-- 货品选择模态框 -->
    <el-dialog v-model="goodsModalVisible" title="选择出库货品">
        <div style="margin-bottom: 15px;">
            <el-input v-model="goodsSearch" placeholder="搜索货品名称/编号" style="width: 300px;"></el-input>
            <el-button type="primary" v-on:click="searchGoods" style="margin-left: 10px;">搜索</el-button>
        </div>
        <el-table :data="goodsList" style="width: 100%" v-on:selection-change="handleGoodsSelection"
                  ref="goodsTable" stripe border>
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" width="70">
                <template #default="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column prop="goodsName" label="货品名称" width="120"></el-table-column>
            <el-table-column prop="goodsCode" label="货品编号" width="150"></el-table-column>
            <el-table-column prop="specification" label="规格型号" width="100"></el-table-column>
            <el-table-column prop="goodsTypeName" label="货品类型" width="100"></el-table-column>
            <el-table-column prop="currentStock" label="当前库存" width="120" align="right" :formatter="formatNumber"></el-table-column>
        </el-table>
        <template #footer>
            <span class="dialog-footer">
                <el-button v-on:click="goodsModalVisible = false">取消</el-button>
                <el-button type="primary" v-on:click="confirmGoodsSelection">确认添加</el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="relatedOrderModalVisible" title="选择订单">
        <div style="margin-bottom: 15px; display: flex; flex-wrap: wrap; gap: 10px;">
            <el-input v-model="salesOrderSearchNo"
                      placeholder="单号"
                      style="width: 200px;" />
            <el-select v-model="salesOrderStatus"
                       placeholder="单据状态"
                       style="width: 150px;">
                <el-option label="未出库" value="未出库" />
                <el-option label="部分出库" value="部分出库" />
            </el-select>
            <el-input v-model="salesOrderCustomer"
                      placeholder="客户名称"
                      style="width: 200px;" />
            <el-button type="primary" v-on:click="searchSalesOrders" style="margin-left: 10px;">查询</el-button>
            <el-button type="text" v-on:click="resetSalesOrderSearch">重置</el-button>
        </div>
        <el-table :data="salesOrderList" style="width: 100%" v-on:selection-change="handleSalesOrderSelection"
                  ref="goodsTable" border>
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="salesOrderNo" label="销售单号" width="150"></el-table-column>
            <el-table-column prop="orderStatus" label="单据状态" width="100">
                <template #default="scope">
                    <span :class="['status-tag', getStatusClass(scope.row.orderStatus)]">
                        {{ getStatusText(scope.row.orderStatus) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="salesDate" label="销售日期" width="120">
                <template #default="scope">
                    {{ formatDate(scope.row.salesDate) }}
                </template>
            </el-table-column>
            <el-table-column prop="customerName" label="客户名称" width="150"></el-table-column>
            <el-table-column prop="sellerShortName" label="销售部门" width="120"></el-table-column>
            <el-table-column prop="sellerBy" label="销售负责人" width="120"></el-table-column>
            <el-table-column prop="salesQuantity" label="销售数量" width="100" align="right" :formatter="formatNumber"></el-table-column>
            <el-table-column prop="salesAmount" label="销售金额" width="120" align="right" :formatter="formatNumber"></el-table-column>
        </el-table>
        <template #footer>
            <span class="dialog-footer">
                <el-button v-on:click="relatedOrderModalVisible = false">取消</el-button>
                <el-button type="primary" v-on:click="confirmSalesOrderSelection">确认选择</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 经办人选择模态框 -->
    <el-dialog v-model="operatorModalVisible" title="选择经办人" width="80%">
        <div style="display: flex; height: 500px;">
            <!-- 左侧：部门树 -->
            <div style="width: 30%; border-right: 1px solid #e5e7eb; padding: 10px;">
                <h4>部门</h4>
                <div class="search-input">
                    <el-input v-model="operatorDepartSearchKey" placeholder="搜索部门" clearable />
                </div>
                <div class="tree-container">
                    <el-tree :data="filteredOperatorDepartData"
                             :props="defaultProps"
                             node-key="id"
                             :highlight-current="true"
                             :expand-on-click-node="false"
                             v-on:node-click="handleOperatorDepartClick"
                             :filter-node-method="filterOperatorDepartNode" />
                </div>
            </div>

            <!-- 中间：人员列表 -->
            <div style="width: 40%; border-right: 1px solid #e5e7eb; padding: 10px;">
                <h4>人员</h4>
                <div class="search-input">
                    <el-input v-model="operatorManSearchKey" placeholder="搜索人员" clearable />
                </div>
                <div class="tree-container" style="max-height: 400px; overflow-y: auto;">
                    <el-table :data="filteredOperatorManData" style="width: 100%" height="400">
                        <el-table-column prop="usersTrueName" label="姓名" width="120"></el-table-column>
                        <el-table-column prop="orgName" label="部门" width="180"></el-table-column>
                        <el-table-column label="操作" width="80">
                            <template #default="scope">
                                <el-button type="primary" size="small"
                                           v-on:click="addOperatorMan(scope.row)">选择</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>

            <!-- 右侧：已选择人员 -->
            <div style="width: 30%; padding: 10px;">
                <h4>已选择人员</h4>
                <div class="selected-person-list" style="max-height: 400px; overflow-y: auto;">
                    <div v-for="(person, index) in selectedOperatorList"
                         :key="person.usersId"
                         class="selected-person-item">
                        <div class="person-info">
                            <span>{{ person.usersTrueName }}</span>
                            <span style="color: #909399; font-size: 12px; margin-left: 8px;">
                                {{ person.orgName }}
                            </span>
                        </div>
                        <el-button type="text"
                                   style="color: #F56C6C;"
                                   v-on:click="removeOperatorMan(index)">移除</el-button>
                    </div>
                    <div v-if="selectedOperatorList.length === 0" class="empty-tip">
                        暂无选择人员
                    </div>
                </div>
            </div>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button v-on:click="operatorModalVisible = false">取消</el-button>
                <el-button type="primary" v-on:click="confirmOperatorSelection">确认选择</el-button>
            </span>
        </template>
    </el-dialog>
</div>

<script>
    const { createApp, ref, onMounted, computed, reactive,watch } = Vue;
    const { ElMessage, ElMessageBox, ElIcon, Search, Document } = ElementPlus;

    const STATUS_CONFIG = {
            '0': { text: '草稿', class: 'status-draft' },
            '1': { text: '待审核', class: 'status-pending' },
            '2': { text: '驳回', class: 'status-rejected' },
            '3': { text: '正常', class: 'status-normal' },
            '4': { text: '停用', class: 'status-disabled' }
    };

    const app = createApp({
        components: {
            ElIcon,
            Search,
            Document
        },
        setup() {
            // 处理本次出库数量输入验证
            const validateOutStockQuantity = (row) => {
                const currentOutStockQty = Number(row.currentOutStockQty) || 0;
                const availableStock = Number(row.availableStock) || 0;

                // 验证出库数量不能大于可用库存
                row.hasStockError = currentOutStockQty > availableStock;

                // 如果关联销售订单，还需要验证不能大于未出库数量
                if (isRelateOutboundOrder.value) {
                    const nonOutboundQuantity = Number(row.nonOutboundQuantity) || 0;
                    if (currentOutStockQty > nonOutboundQuantity) {
                        row.hasStockError = true;
                        ElMessage.warning(`本次出库数量不能大于未出库数量 ${nonOutboundQuantity}`);
                    }
                }

                if (row.hasStockError) {
                    ElMessage.warning(`本次出库数量不能大于可用库存 ${availableStock}`);
                }
            };

            // 收货人选项
            const consigneeOptions = ref([]);

            // 加载收货人数据
            const loadConsigneeData = async () => {
                try {
                    const response = await axios.post('/WhOutbound/UserAll');

                    if (response.data.code === 200) {
                        consigneeOptions.value = response.data.data;
                    } else {
                        console.error('收货人数据格式错误:', response.data);
                        ElMessage.error('加载收货人数据失败');
                    }
                } catch (error) {
                    console.error('加载收货人数据失败:', error);
                    ElMessage.error('加载收货人数据失败');
                }
            };

            // 收货人选择变化处理
            const handleConsigneeChange = (value) => {
                if (value && value.length > 0) {
                    const selectedId = value[value.length - 1]; // 获取最后选择的ID

                    // 在树形数据中查找选中的收货人
                    const findConsigneeInTree = (nodes, targetId) => {
                        for (const node of nodes) {
                            if (node.id === targetId) {
                                return node;
                            }
                            if (node.children && node.children.length > 0) {
                                const found = findConsigneeInTree(node.children, targetId);
                                if (found) return found;
                            }
                        }
                        return null;
                    };

                    const selectedConsignee = findConsigneeInTree(consigneeOptions.value, selectedId);

                    if (selectedConsignee) {
                        form.value.contactInfo = selectedConsignee.honeUmber ||
                                               selectedConsignee.phone ||
                                               selectedConsignee.contactInfo ||
                                               selectedConsignee.mobile ||
                                               '';
                    } else {
                        form.value.contactInfo = '';
                    }
                } else {
                    form.value.contactInfo = '';
                }
            };

            // 经办人选择相关
            const operatorModalVisible = ref(false);
            const operatorDepartSearchKey = ref('');
            const operatorManSearchKey = ref('');
            const selectedOperatorList = ref([]);
            const currentOperatorDepart = ref(null);

            // 计算属性：过滤部门数据
            const filteredOperatorDepartData = computed(() => {
                if (!operatorDepartSearchKey.value) return departData.value;
                const keyword = operatorDepartSearchKey.value.toLowerCase();

                const filterTree = (nodes) => {
                    return nodes
                        .filter(node => {
                            const matchSelf = node.name?.toLowerCase().includes(keyword) ||
                                            node.label?.toLowerCase().includes(keyword);
                            const filteredChildren = filterTree(node.children || []);
                            return matchSelf || filteredChildren.length > 0;
                        })
                        .map(node => ({
                            ...node,
                            children: filterTree(node.children || [])
                        }));
                };

                return filterTree(departData.value);
            });

            // 计算属性：过滤人员数据
            const filteredOperatorManData = computed(() => {
                let filteredData = manData.value;

                // 先按部门过滤
                if (currentOperatorDepart.value) {
                    filteredData = filteredData.filter(man =>
                        man && man.orgId && String(man.orgId) === String(currentOperatorDepart.value.id)
                    );
                }

                // 再按搜索关键词过滤
                if (operatorManSearchKey.value) {
                    const keyword = operatorManSearchKey.value.toLowerCase();
                    filteredData = filteredData.filter(man =>
                        man.usersTrueName?.toLowerCase().includes(keyword)
                    );
                }

                return filteredData;
            });

            // 部门节点点击
            const handleOperatorDepartClick = (data) => {
                currentOperatorDepart.value = data;
            };

            // 部门搜索过滤方法
            const filterOperatorDepartNode = (value, data) => {
                if (!value) return true;
                return data.name?.toLowerCase().includes(value.toLowerCase()) ||
                       data.label?.toLowerCase().includes(value.toLowerCase());
            };

            // 添加经办人
            const addOperatorMan = (man) => {
                // 检查是否已存在
                const exists = selectedOperatorList.value.some(item => item.usersId === man.usersId);
                if (!exists) {
                    selectedOperatorList.value.push({
                        usersId: man.usersId,
                        usersTrueName: man.usersTrueName,
                        orgName: man.orgName
                    });
                } else {
                    ElMessage.warning('该人员已选择');
                }
            };

            // 移除经办人
            const removeOperatorMan = (index) => {
                selectedOperatorList.value.splice(index, 1);
            };

            // 打开经办人模态框
            const openOperatorModal = () => {
                operatorModalVisible.value = true;
                operatorDepartSearchKey.value = '';
                operatorManSearchKey.value = '';
                currentOperatorDepart.value = null;

                // 如果已有选择的经办人，初始化选择列表
                if (form.value.operator) {
                    const selectedMan = manData.value.find(man =>
                        man && man.usersId && String(man.usersId) === String(form.value.operator)
                    );
                    if (selectedMan) {
                        selectedOperatorList.value = [{
                            usersId: selectedMan.usersId,
                            usersTrueName: selectedMan.usersTrueName,
                            orgName: selectedMan.orgName || '未知部门'
                        }];
                    }
                } else {
                    selectedOperatorList.value = [];
                }
            };

            // 确认经办人选择
            const confirmOperatorSelection = () => {
                if (selectedOperatorList.value.length === 0) {
                    ElMessage.warning('请至少选择一个经办人');
                    return;
                }

                // 目前只支持单选，取第一个选择的人员
                const selectedPerson = selectedOperatorList.value[0];
                form.value.operator = selectedPerson.usersId;
                form.value.operatorName = selectedPerson.usersTrueName;

                operatorModalVisible.value = false;
                ElMessage.success('经办人选择成功');
            };

            // 新增：关联出库单号复选框绑定变量
            const isRelateOutboundOrder = ref(false);

            // 日期格式化（仅日期）
            const formatDate = (date) => {
                if (!date) return '';
                const dt = new Date(date);
                const year = dt.getFullYear();
                const month = String(dt.getMonth() + 1).padStart(2, '0');
                const day = String(dt.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            };

            // 正确的格式化函数
            const formatNumber = (row, column, cellValue) => {
                // 获取实际的值
                const value = cellValue !== undefined ? cellValue : (0);

                if (value === null || value === undefined || isNaN(Number(value))) {
                    return '0.00';
                }

                const numValue = Number(value);
                return numValue.toFixed(2);
            };

            // 创建表单
            const form = ref({
                outboundOrderId: 0,
                outboundOrderNo: '',
                warehouseId: '',
                outboundDate: new Date().toISOString().split('T')[0],
                customerId: '',
                customerName: '',
                customerContact: '',
                customerPhone: '',
                outboundDept: '',
                outboundBy: '',
                orderStatus: '1', // 默认待审核状态
                auditorBy: 0,
                auditorTime: '',
                auditorComment: '',
                isDelete: '0',
                createBy: 'admin',
                createTime: new Date(),
                updateBy: 'admin',
                updateTime: new Date(),
                remarks: ''
            });

            // 从出库页面提取的部门和人员选择功能
            const outboundDepartVisible = ref(false);
            const outboundManVisible = ref(false);
            const goodsModalVisible = ref(false);

            const selectedDepart = ref('');
            const selectedMan = ref('');
            const selectedManName = ref('');
            const currentDepart = ref(null);
            const selectedOrgName = ref('');
            const selectedDepartOrgId = ref(null);
            const flatDepartList = ref([]);
            const filteredManData = ref([]);
            const selectedManId = ref('');

            // 搜索关键词
            const departSearchKey = ref('');
            const manSearchKey = ref('');
            const goodsSearch = ref('');

            // 部门数据
            const departData = ref([]);
            const defaultProps = ref({
                children: 'children',
                label: 'label'
            });

            // 人员数据
            const manData = ref([]);

            // 出库明细相关
            const outboundDetails = ref([]);
            const selectedDetails = ref([]);
            const goodsList = ref([]);
            const selectedGoods = ref([]);

            // 附件相关
            const fileInput = ref(null);
            const uploadedFiles = ref([]);

            // 客户选项
            const customerOptions = ref([]);

            // 计算属性
            const totalQuantity = computed(() => {
                return outboundDetails.value.reduce((sum, item) => sum + (Number(item.orderQuantity) || 0), 0);
            });

            // 新增：出库类型选项
            const outboundTypeOptions = ref([]);

            // 新增：状态选项
            const statusOptions = ref([]);

            // 经办人选项
            const operatorOptions = ref([]);

            // 仓库选项
            const warehouseOptions = ref([]);

            // 修改 loadDictData 函数，移除原仓库加载逻辑
            const loadDictData = async () => {
              try {
                const response = await axios.post('/WhOutbound/GetDictData');
                if (response.data.code === 200) {
                  // 绑定出库类型
                  outboundTypeOptions.value = response.data.data.outboundTypes || [];
                  // 绑定状态选项
                  statusOptions.value = response.data.data.statusList || [];
                }
              } catch (error) {
                console.error('加载字典数据失败:', error);
                ElMessage.error('加载字典数据失败');
              }
            };

            // 加载仓库数据
            const loadWarehouseData = async () => {
              try {
                // 获取仓库列表
                const warehouseRes = await axios.post('/BiProduct/WhAll');
                if (warehouseRes.data.code === 200) {
                  warehouseOptions.value = warehouseRes.data.data;
                }
              } catch (error) {
                console.error('加载仓库数据失败：', error);
                ElMessage.error('加载仓库数据失败');
              }
            };

            // 仓库选择变化处理
            const handleWarehouseChange = async (warehouseId) => {
                if (!warehouseId) return;

                // 如果已经选择了销售订单，重新加载该仓库下的可出库货品
                if (form.value.relatedOrderNo) {
                    await loadAvailableGoodsByWarehouse(warehouseId);
                }
            };

            // 根据仓库加载可出库货品
            const loadAvailableGoodsByWarehouse = async (warehouseId) => {
                try {
                    const response = await axios.post(`/WhOutbound/GetAvailableGoodsBySalesOrder?salesOrderNo=${form.value.relatedOrderNo}&warehouseId=${warehouseId}`);
                    if (response.data.code === 200) {
                        processGoodsData(response.data.data);
                    } else {
                        ElMessage.error('加载可出库货品失败：' + response.data.msg);
                    }
                } catch (error) {
                    console.error('加载可出库货品失败:', error);
                    ElMessage.error('加载可出库货品失败，请重试');
                }
            };

            // 出库类型变化处理
            const handleOutboundTypeChange = (newVal) => {
                if (newVal !== '0') { // 如果不是销售出库类型
                    form.value.relatedOrderNo = '';
                    form.value.customerName = '';
                    isRelateOutboundOrder.value = false;
                    outboundDetails.value = [];
                }
            };

            const loadData = async () => {
                try {
                    // 先加载字典数据（不含仓库）
                    await loadDictData();
                    // 单独加载仓库列表
                    await loadWarehouseData();
                    // 加载收货人数据
                    await loadConsigneeData();

                    await loadDepartData();
                    await loadManData();
                    const currentUserId = getCurrentUserId();
                    form.value.createBy = currentUserId;
                    form.value.updateBy = currentUserId;

                    // 生成出库单号（新增场景）
                    const orderId = getOrderIdFromUrl();
                    if (!orderId) {
                        await generateOrderNo();
                    } else {
                        // 编辑场景：加载已有数据（含状态）
                        await loadEditData(orderId);
                    }

                    // 加载客户列表、货品列表（原有逻辑不变）
                    const customerRes = await axios.post('/BiProduct/CustomerAll');
                    if (customerRes.data.code === 200) {
                        customerOptions.value = customerRes.data.data;
                    }
                    const goodsRes = await axios.post('/BiProduct/GetAll');
                    if (goodsRes.data.code === 200) {
                        goodsList.value = goodsRes.data.data.result;
                    }
                } catch (error) {
                    ElMessage.error('数据加载失败，请刷新重试');
                    console.error(error);
                }
            };

            // 计算属性：部门搜索过滤
            const filteredDepartData = computed(() => {
                if (!departSearchKey.value) return departData.value;
                const keyword = departSearchKey.value.toLowerCase();

                const filterTree = (nodes) => {
                    return nodes
                        .filter(node => {
                            const matchSelf = node.name?.toLowerCase().includes(keyword) ||
                                            node.label?.toLowerCase().includes(keyword);
                            const filteredChildren = filterTree(node.children || []);
                            return matchSelf || filteredChildren.length > 0;
                        })
                        .map(node => ({
                            ...node,
                            children: filterTree(node.children || [])
                        }));
                };

                return filterTree(departData.value);
            });

            // 计算属性：人员搜索过滤
            const searchFilteredManData = computed(() => {
                if (!manSearchKey.value) return filteredManData.value;
                const keyword = manSearchKey.value.toLowerCase();
                return filteredManData.value.filter(man => {
                    return man.usersTrueName?.toLowerCase().includes(keyword);
                });
            });

            // 合计：出库种类（明细总条数）
            const totalCategories = computed(() => {
              return outboundDetails.value.length;
            });

            // 合计：出库数量（本次出库数量之和）
            const outboundTotalQuantity = computed(() => {
              return outboundDetails.value.reduce((sum, item) => {
                return sum + (Number(item.currentOutStockQty) || 0);
              }, 0);
            });

            // 合计：已出库数量（所有明细已出库数量之和）
            const outboundQuantity = computed(() => {
              return outboundDetails.value.reduce((sum, item) => {
                return sum + (Number(item.outboundQuantity) || 0);
              }, 0);
            });

            // 合计：未出库数量（所有明细未出库数量之和）
            const nonOutboundQuantity = computed(() => {
              return outboundDetails.value.reduce((sum, item) => {
                return sum + (Number(item.nonOutboundQuantity) || 0);
              }, 0);
            });

            // 合计：销售金额（所有明细出库金额之和）
            const totalAmount = computed(() => {
              return outboundDetails.value.reduce((sum, item) => {
                const amount = item.outboundUnitPrice && item.currentOutStockQty
                  ? Number(item.outboundUnitPrice) * Number(item.currentOutStockQty)
                  : 0;
                return sum + amount;
              }, 0);
            });

            // 计算单条明细出库金额
            const calculateOutboundAmount = (row) => {
              const price = Number(row.outboundUnitPrice) || 0;
              const quantity = Number(row.currentOutStockQty) || 0;
              return (price * quantity).toFixed(2);
            };

            // 部门节点点击
            const departNode = (data) => {
                currentDepart.value = data;
                selectedDepartOrgId.value = data.id;
                departData.value.forEach(node => {
                    node.highlight = node.id === data.id;
                });
            };

            // 确认部门选择
            const confirmDepart = () => {
                if (currentDepart.value) {
                    selectedDepart.value = currentDepart.value.label;
                    selectedDepartOrgId.value = currentDepart.value.id;
                    selectedOrgName.value = currentDepart.value.label;

                    // 更新表单中的出库部门
                    form.value.outboundDept = currentDepart.value.id;

                    // 过滤该部门下的人员
                    filteredManData.value = manData.value.filter(man => {
                        return man && String(man.orgId) === String(selectedDepartOrgId.value);
                    });
                    selectedMan.value = '';
                    selectedManName.value = '';
                } else {
                    selectedDepart.value = '';
                    selectedDepartOrgId.value = null;
                    selectedOrgName.value = '';
                    filteredManData.value = manData.value;
                    ElMessage.info('未选择部门，将显示所有人员');
                }
                outboundDepartVisible.value = false;
            };

            // 打开人员模态框
            const openManModal = () => {
                selectedOrgName.value = selectedDepart.value || '';
                outboundManVisible.value = true;
            };

            // 确认人员选择
            const confirmMan = () => {
                if (selectedMan.value) {
                    const selectedManObj = manData.value.find(man => {
                        return man && man.usersId && String(man.usersId) === String(selectedMan.value);
                    });

                    if (!selectedManObj) {
                        ElMessage.error('未找到匹配的人员，请刷新页面重试');
                        outboundManVisible.value = false;
                        return;
                    }
                    selectedManId.value = selectedMan.value;
                    const manOrgId = selectedManObj.orgId;
                    if (!manOrgId) {
                        ElMessage.error('人员部门信息异常');
                        outboundManVisible.value = false;
                        return;
                    }

                    const matchedDepart = flatDepartList.value.find(depart => {
                        return depart && depart.orgId && String(depart.orgId) === String(manOrgId);
                    });

                    if (matchedDepart) {
                        selectedDepart.value = matchedDepart.label;
                        selectedOrgName.value = matchedDepart.label;
                        selectedDepartOrgId.value = manOrgId;

                        // 更新表单中的出库部门和负责人
                        form.value.outboundDept = manOrgId;
                        form.value.outboundBy = selectedManId.value;

                        filteredManData.value = manData.value.filter(man =>
                            man && man.orgId && String(man.orgId) === String(manOrgId)
                        );
                        selectedManName.value = selectedManObj.usersTrueName;
                    } else {
                        ElMessage.error('未找到匹配的部门，请刷新页面重试');
                    }

                    outboundManVisible.value = false;
                } else {
                    ElMessage.warning('请选择人员');
                }
            };

            // 加载部门数据
            const loadDepartData = async () => {
                try {
                    const departRes = await axios.get('/StockUpOrder/GetOrgInfoForSelectTable');
                    departData.value = Array.isArray(departRes.data) ? departRes.data : [];
                    if (departData.value.length === 0) {
                        ElMessage.warning('部门数据为空，请检查接口');
                    }

                    const flattenDepart = (departArray) => {
                        let result = [];
                        departArray.forEach(depart => {
                            if (!depart) return;
                            const flatDepart = {
                                orgId: depart.id || depart.orgId,
                                label: depart.name || depart.label,
                                children: Array.isArray(depart.children) ? depart.children : []
                            };
                            result.push(flatDepart);
                            if (flatDepart.children.length > 0) {
                                result = [...result, ...flattenDepart(flatDepart.children)];
                            }
                        });
                        return result;
                    };
                    flatDepartList.value = flattenDepart(departData.value);
                } catch (err) {
                    console.error('获取部门数据失败：', err);
                    ElMessage.error('网络错误，无法加载部门数据');
                    departData.value = [];
                    flatDepartList.value = [];
                }
            };

            // 加载人员数据
            const loadManData = async () => {
                try {
                    const manRes = await axios.get('/StockUpOrder/GetUserInfoForSelectTable');
                    manData.value = (manRes.data || []).filter(man => man && man.usersId);
                    filteredManData.value = manData.value;
                    if (manData.value.length === 0) {
                        ElMessage.warning('未加载到有效人员数据');
                    }
                } catch (err) {
                    console.error('获取人员数据失败：', err);
                    ElMessage.error('网络错误，无法加载人员数据');
                    manData.value = [];
                    filteredManData.value = [];
                }
            };

            // 客户选择变更
            const handleCustomerChange = (customerId) => {
                const customer = customerOptions.value.find(item => item.id === customerId);
                if (customer) {
                    form.value.customerName = customer.name;
                    form.value.customerContact = customer.contactPerson;
                    form.value.customerPhone = customer.contactPhone;
                }
            };

            // 货品选择相关
            const openGoodsSelectModal = () => {
                goodsModalVisible.value = true;
            };

            const handleGoodsSelection = (val) => {
                selectedGoods.value = val;
            };

            const searchGoods = () => {};

            // 计算出库金额
            const calculateAmount = (row) => {
                const quantity = Number(row.orderQuantity) || 0;
                const price = Number(row.outboundUnitPrice) || 0;
                row.outboundAmount = quantity * price;
                row.unshippedQty = quantity;
            };

            // 明细操作
            const handleDetailSelection = (val) => {
                selectedDetails.value = val;
            };

            const removeDetail = (index) => {
                outboundDetails.value.splice(index, 1);
                ElMessage.success('已移除该货品明细');
            };

            const removeSelectedDetails = () => {
                if (selectedDetails.value.length === 0) {
                    ElMessage.warning('请先勾选要移除的明细');
                    return;
                }

                const codes = selectedDetails.value.map(item => item.goodsCode);
                outboundDetails.value = outboundDetails.value.filter(item => !codes.includes(item.goodsCode));
                ElMessage.success(`已移除${selectedDetails.value.length}条明细`);
                selectedDetails.value = [];
            };

            // 附件上传处理
            const triggerFileInput = () => {
                fileInput.value.click();
            };

            const handleFileUpload = (event) => {
                const files = event.target.files;
                if (!files || files.length === 0) return;

                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    uploadedFiles.value.push({
                        file: file,
                        name: file.name
                    });
                }

                ElMessage.success(`已添加 ${files.length} 个附件到本地`);
                event.target.value = '';
            };

            const removeFile = (index) => {
                uploadedFiles.value.splice(index, 1);
                ElMessage.info('文件已删除');
            };

            // 获取当前用户ID
            const getCurrentUserId = () => {
                const userStr = sessionStorage.getItem('YH');
                if (!userStr) {
                    ElMessage.warning('未检测到登录状态，请重新登录');
                    return '';
                }
                try {
                    const userObj = JSON.parse(userStr);
                    const userId = userObj?.id?.toString() || '';
                    if (!userId) {
                        ElMessage.warning('用户信息不完整，请重新登录');
                    }
                    return userId;
                } catch (error) {
                    console.error('解析用户信息失败：', error);
                    ElMessage.error('用户信息异常，请重新登录');
                    return '';
                }
            };
            // 1. 新增：从URL获取订单ID（编辑场景）
            const getOrderIdFromUrl = () => {
                const urlParams = new URLSearchParams(window.location.search);
                return urlParams.get('id');
            };

            // 2. 新增：加载编辑数据
            const loadEditData = async (orderId) => {
                try {
                    const response = await axios.post(`/WhOutbound/Details?id=${orderId}`);
                    if (response.data.code === 200) {
                        const orderData = response.data.data[0];
                        // 状态回显（直接接收数字字符串，与管理页一致）
                        form.value.orderStatus = orderData.orderStatus || '1';
                    }
                } catch (error) {
                    console.error('加载编辑数据失败:', error);
                }
            };

            // 修改验证函数，加强库存验证
            const validateForm = () => {
                if (!form.value.outboundType) {
                    ElMessage.error('请选择出库类型');
                    return false;
                }
                if (!form.value.warehouseId) {
                    ElMessage.error('请选择仓库名称');
                    return false;
                }
                if (!form.value.outboundDate) {
                    ElMessage.error('请选择出库日期');
                    return false;
                }
                if (outboundDetails.value.length === 0) {
                    ElMessage.error('请至少添加一条出库货品明细');
                    return false;
                }

                // 详细验证明细数据
                for (let i = 0; i < outboundDetails.value.length; i++) {
                    const item = outboundDetails.value[i];
                    const currentOutStockQty = Number(item.currentOutStockQty) || 0;
                    const availableStock = Number(item.availableStock) || 0;

                    if (!item.currentOutStockQty || item.currentOutStockQty <= 0) {
                        ElMessage.error(`第${i + 1}行货品「${item.goodsName}」出库数量必须大于0`);
                        return false;
                    }

                    // 严格验证库存
                    if (currentOutStockQty > availableStock) {
                        ElMessage.error(`第${i + 1}行货品「${item.goodsName}」库存不足，当前可用库存${availableStock}，出库数量${currentOutStockQty}`);
                        return false;
                    }

                    // 关联销售订单时，验证不能大于未出库数量
                    if (isRelateOutboundOrder.value) {
                        const nonOutboundQuantity = Number(item.nonOutboundQuantity) || 0;
                        if (currentOutStockQty > nonOutboundQuantity) {
                            ElMessage.error(`第${i + 1}行货品「${item.goodsName}」出库数量不能大于未出库数量${nonOutboundQuantity}`);
                            return false;
                        }
                    }
                }

                return true;
            };

            const closePage = () => {
                window.history.back();
            };

            // 重置表单函数
            const resetForm = () => {
                form.value = {
                    outboundOrderId: 0,
                    outboundOrderNo: '',
                    warehouseId: '',
                    outboundDate: new Date().toISOString().split('T')[0],
                    customerId: '',
                    customerName: '',
                    customerContact: '',
                    customerPhone: '',
                    outboundDept: '',
                    outboundBy: '',
                    orderStatus: '1',
                    auditorBy: 0,
                    auditorTime: '',
                    auditorComment: '',
                    isDelete: '0',
                    createBy: getCurrentUserId(),
                    createTime: new Date(),
                    updateBy: getCurrentUserId(),
                    updateTime: new Date(),
                    remarks: ''
                };
                outboundDetails.value = [];
                uploadedFiles.value = [];
                selectedDepart.value = '';
                selectedManName.value = '';
                selectedMan.value = '';
                isRelateOutboundOrder.value = false;

                // 重新生成单号
                generateOrderNo();
            };

            // 生成订单号函数
            const generateOrderNo = async () => {
                try {
                    const orderNoRes = await axios.post('/NumberingRules/GenerateByRuleId?ruleId=3');
                    if (orderNoRes.data && orderNoRes.data.success) {
                        form.value.outboundOrderNo = orderNoRes.data.number;
                    }
                } catch (error) {
                    console.error('生成出库单号失败：', error);
                }
            };

            const relatedOrderModalVisible = ref(false); // 控制模态框显示/隐藏
            const salesOrderSearchNo = ref(''); // 销售单号查询关键词
            const salesOrderStatus = ref(''); // 单据状态查询
            const salesOrderCustomer = ref(''); // 客户名称查询
            const salesOrderList = ref([]); // 销售单列表
            const selectedSalesOrders = ref([]); // 选中的销售单

            // 修改打开关联订单模态框的函数
            const openRelatedOrderModal = () => {
                // 只有在销售出库类型时才允许选择关联订单
                if (!isSalesOutbound.value) {
                    ElMessage.warning('只有销售出库类型才能关联销售订单');
                    return;
                }

                relatedOrderModalVisible.value = true;
                // 重置搜索条件
                resetSalesOrderSearch();
                // 加载销售订单数据
                searchSalesOrders();
            };

            // 修改查询销售单函数，添加类型检查
            const searchSalesOrders = async () => {
                // 再次确认是销售出库类型
                if (!isSalesOutbound.value) {
                    ElMessage.warning('当前出库类型不支持关联销售订单');
                    return;
                }

                try {
                    const response = await axios.post('/WhOutbound/GetSalesOrerAll');
                    if (response.data.code === 200) {
                        // 过滤掉已完全出库的销售订单（所有明细未出库数量都为0的订单）
                        salesOrderList.value = response.data.data.filter(order => {
                            // 这里可以根据实际业务逻辑判断订单是否还有未出库的货品
                            // 假设订单对象中有个字段表示是否还有未出库数量
                            return order.hasUnshippedGoods !== false; // 根据实际接口返回的字段调整
                        });

                        if (salesOrderList.value.length === 0) {
                            ElMessage.info('没有找到包含未出库货品的销售订单');
                        }
                    } else {
                        ElMessage.error('加载销售订单失败：' + response.data.msg);
                    }
                } catch (error) {
                    console.error('查询销售订单出错:', error);
                    ElMessage.error('查询销售订单失败，请重试');
                }
            };

            // 在 setup() 函数中添加计算属性来判断是否为销售出库类型
            const isSalesOutbound = computed(() => {
                return form.value.outboundType === '0';
            });

            // 监听关联出库单号复选框变化
            watch(isRelateOutboundOrder, (newVal) => {
                if (newVal) {
                    // 勾选时，将所有货品单位设置为"个"
                    outboundDetails.value.forEach(item => {
                        item.unit = '个';
                    });
                }
            });

            // 重置销售单查询条件
            const resetSalesOrderSearch = () => {
                salesOrderSearchNo.value = '';
                salesOrderStatus.value = '';
                salesOrderCustomer.value = '';
                // 重新加载数据
                searchSalesOrders();
            };

            // 处理销售单选中事件
            const handleSalesOrderSelection = (val) => {
                selectedSalesOrders.value = val;
            };

            // 修改 confirmSalesOrderSelection 函数
            const confirmSalesOrderSelection = async () => {
                if (selectedSalesOrders.value.length > 0) {
                    const selectedOrder = selectedSalesOrders.value[0];
                    form.value.relatedOrderNo = selectedOrder.salesOrderNo;
                    form.value.customerName = selectedOrder.customerName;

                    // 如果已经选择了仓库，则加载该仓库下的可出库货品
                    if (form.value.warehouseId) {
                        await loadAvailableGoodsByWarehouse(form.value.warehouseId);
                    } else {
                        ElMessage.warning('请先选择仓库');
                    }

                    relatedOrderModalVisible.value = false;
                } else {
                    ElMessage.warning('请选择销售单');
                }
            };

            // 处理货品数据
            const processGoodsData = (availableGoods) => {
                outboundDetails.value = [];

                // 过滤未出库数量大于0的货品
                const filteredGoods = availableGoods.filter(item =>
                    Number(item.nonOutboundQuantity) > 0
                );

                if (filteredGoods.length === 0) {
                    ElMessage.warning('所选销售订单中没有可出库的货品（未出库数量均为0）');
                    return;
                }

                // 如果过滤后有货品被移除，显示提示信息
                if (filteredGoods.length < availableGoods.length) {
                    const removedCount = availableGoods.length - filteredGoods.length;
                    ElMessage.info(`已过滤掉${removedCount}个未出库数量为0的货品`);
                }

                filteredGoods.forEach(item => {
                    outboundDetails.value.push({
                        // 基础信息
                        goodsCode: item.goodsCode,
                        goodsName: item.goodsName,
                        specification: item.specification,
                        goodsTypeName: item.goodsTypeName,
                        goodsId: item.goodsId,

                        // 数量信息
                        salesQuantity: item.salesQuantity || 0,
                        outboundQuantity: item.outboundQuantity || 0,
                        nonOutboundQuantity: item.nonOutboundQuantity || 0,
                        currentOutStockQty: 0,

                        // 库存和价格信息
                        availableStock: item.availableStock || 0,
                        outboundUnitPrice: item.outboundUnitPrice || 0,

                        // 仓库和库位信息（直接使用查询结果）
                        warehouseId: item.warehouseId,
                        warehouseName: item.warehouseName,
                        storageLocationId: item.storageLocationId,
                        storageLocationName: item.storageLocationName,

                        // 其他字段
                        unit: '个',
                        remarks: '',
                        isDelete: '0',
                        attachmentId: 0,

                        // 前端使用的字段
                        outboundDetailId: 0,
                        outboundOrderId: 0,
                        goodsTypeId: item.goodsId || 0
                    });
                });

                ElMessage.success(`已加载${filteredGoods.length}个可出库货品`);
            };

    const confirmGoodsSelection = () => {
        if (selectedGoods.value.length === 0) {
            ElMessage.warning('请至少选择一个货品');
            return;
        }

        // 检查货品状态
        const invalidGoods = selectedGoods.value.filter(goods => parseInt(goods.status) !== 3);
        if (invalidGoods.length > 0) {
            const invalidNames = invalidGoods.map(g => g.goodsName).join('、');
            ElMessage.error(`以下货品状态异常，无法添加：${invalidNames}`);
            return;
        }

        const existingCodes = outboundDetails.value.map(item => item.goodsCode);

        // 过滤掉库存为0的货品
        const availableGoods = selectedGoods.value.filter(goods =>
            (goods.currentStock || 0) > 0 &&
            !existingCodes.includes(goods.goodsCode)
        );

        // 检查是否有货品因为库存为0被过滤
        const zeroStockGoods = selectedGoods.value.filter(goods =>
            (goods.currentStock || 0) <= 0 &&
            !existingCodes.includes(goods.goodsCode)
        );

        if (zeroStockGoods.length > 0) {
            const zeroStockNames = zeroStockGoods.map(g => g.goodsName).join('、');
            ElMessage.warning(`以下货品库存为0，无法添加：${zeroStockNames}`);
        }

        // 检查重复添加
        if (availableGoods.length === 0) {
            if (zeroStockGoods.length > 0) {
                ElMessage.warning('所选货品库存为0或已全部存在于出库明细中');
            } else {
                ElMessage.warning('所选货品已全部存在于出库明细中');
            }
            goodsModalVisible.value = false;
            selectedGoods.value = [];
            return;
        }

        availableGoods.forEach(goods => {
            outboundDetails.value.push({
                outboundDetailId: 0,
                outboundOrderId: 0,
                goodsCode: goods.goodsCode,
                goodsName: goods.goodsName,
                specification: goods.specification,
                goodsType: goods.goodsTypeName,
                goodsTypeId: goods.goodsId,
                currentStock: goods.currentStock || 0,
                availableStock: goods.currentStock || 0,
                unit: isRelateOutboundOrder.value ? '个' : (goods.unit || '个'),
                salesQuantity: goods.salesQuantity || 0,
                orderQuantity: 1,
                outboundUnitPrice: goods.outboundReferencePrice || 0,
                outboundAmount: (goods.outboundReferencePrice || 0) * 1,
                outboundQuantity: 0,
                nonOutboundQuantity: 1,
                currentOutStockQty: 0,
                storageLocationId: 0,
                warehouseId: goods.warehouseId,
                storageLocationName: '',
                hasStockError: false,
                isDelete: '0',
                attachmentId: 0,
                remarks: ''
            });
        });

        ElMessage.success(`成功添加${availableGoods.length}个货品`);
        goodsModalVisible.value = false;
        selectedGoods.value = [];
    };

            // 处理出库数量输入事件
            const handleOutboundQuantityInput = (row) => {
                // 当关联销售订单时，确保单位为"个"
                if (isRelateOutboundOrder.value) {
                    row.unit = '个';
                }

                // 计算未出库数量
                row.nonOutboundQuantity = (row.salesQuantity || row.orderQuantity) - (row.outboundQuantity || 0);
            };

            // 处理本次出库数量输入事件
            const handleCurrentOutStockQtyInput = (row) => {
                // 当关联销售订单时，确保单位为"个"
                if (isRelateOutboundOrder.value) {
                    row.unit = '个';
                }

                // 实时验证
                validateOutStockQuantity(row);
            };

            // 初始化加载
            onMounted(() => {
                loadData();
            });

            // 销售订单状态配置（与销售订单管理页面保持一致）
            const salesOrderStatusConfig = {
                '0': { text: '草稿', class: 'status-draft' },
                '1': { text: '待审核', class: 'status-pending' },
                '2': { text: '已驳回', class: 'status-rejected' },
                '3': { text: '已审核', class: 'status-approved' },
                '4': { text: '部分出库', class: 'status-closed' }
            };

            // 获取状态文本
            const getStatusText = (status) => {
                return salesOrderStatusConfig[status]?.text || '未知状态';
            };

            // 获取状态样式类
            const getStatusClass = (status) => {
                return salesOrderStatusConfig[status]?.class || '';
            };
            // 在 setup() 函数中添加
            const submitting = ref(false);

            // 提交表单函数
            const submitForm = async (isAddNew = false) => {
                if (submitting.value) {
                    ElMessage.warning('正在提交，请勿重复操作');
                    return;
                }

                if (!validateForm()) return;

                submitting.value = true;

                try {
                    // 构建明细数据
                    const submitDetails = [];

                    outboundDetails.value.forEach(detail => {
                        submitDetails.push({
                            StockOutDetailId: 0,
                            StockOutOrderId: 0,
                            BatchId: 0,
                            GoodsCode: detail.goodsCode,
                            ProductUnit: detail.unit,
                            StorageLocationId: detail.storageLocationId,
                            OutStockUnitPrice: detail.outboundUnitPrice,
                            OutStockQuantity: detail.currentOutStockQty,
                            BatchNo: '', // 批次号设为空字符串
                            ProductionDate: new Date().toISOString().split('T')[0],
                            IsDelete: '0',
                            CreateBy: form.value.createBy,
                            CreateTime: new Date().toISOString(),
                            UpdateBy: form.value.updateBy,
                            UpdateTime: new Date().toISOString(),
                            AttachmentId: 0,
                            Remarks: detail.remarks || ''
                        });
                    });

                    // 构建提交数据
                    const submitData = {
                        Outbound: {
                            StockOutOrderId: form.value.outboundOrderId,
                            StockOutOrderNo: form.value.outboundOrderNo,
                            WarehouseId: form.value.warehouseId,
                            SourceOrderNo: form.value.relatedOrderNo,
                            StockOutType: form.value.outboundType,
                            StockOutDate: form.value.outboundDate,
                            OperatorBy: form.value.operator,
                            OrderStatus: form.value.orderStatus,
                            AuditorBy: 0,
                            AuditorTime: new Date().toISOString(),
                            AuditorComment: '',
                            IsDelete: '0',
                            CreateBy: form.value.createBy,
                            CreateTime: new Date().toISOString(),
                            UpdateBy: form.value.updateBy,
                            UpdateTime: new Date().toISOString(),
                            Remarks: form.value.remarks
                        },
                        Details: submitDetails
                    };

                    const response = await axios.post("/WhOutbound/CreateOutbound", submitData);
                    if (response.data.code === 200) {
                        ElMessage.success('出库订单提交成功！');
                        if (isAddNew) {
                            resetForm();
                        } else {
                            closePage();
                        }
                    } else {
                        ElMessage.error('提交失败: ' + response.data.msg);
                    }
                } catch (error) {
                    console.error('提交错误:', error);
                    ElMessage.error('提交失败，请重试');
                } finally {
                    submitting.value = false;
                }
            };

            // 修改保存草稿和保存并新增函数
            const saveDraft = async () => {
                form.value.orderStatus = '0';
                await submitForm(false);
            };

            const saveAndAdd = async () => {
                form.value.orderStatus = '1';
                await submitForm(true);
            };

            return {
                form,
                submitting,
                outboundDetails,
                selectedDetails,
                totalQuantity,
                totalAmount,
                customerOptions,
                goodsList,
                goodsModalVisible,
                goodsSearch,
                handleCustomerChange,
                openGoodsSelectModal,
                handleGoodsSelection,
                searchGoods,
                confirmGoodsSelection,
                calculateAmount,
                handleDetailSelection,
                removeDetail,
                removeSelectedDetails,
                fileInput,
                uploadedFiles,
                triggerFileInput,
                handleFileUpload,
                removeFile,
                submitForm,
                saveDraft,
                saveAndAdd,
                closePage,
                formatNumber,
                outboundDepartVisible,
                outboundManVisible,
                selectedDepart,
                selectedMan,
                selectedManName,
                departData,
                manData,
                defaultProps,
                departNode,
                confirmDepart,
                confirmMan,
                openManModal,
                selectedOrgName,
                departSearchKey,
                manSearchKey,
                filteredDepartData,
                searchFilteredManData,
                nonOutboundQuantity,
                outboundQuantity,
                totalCategories,
                calculateOutboundAmount,
                outboundTypeOptions,
                statusOptions,
                operatorOptions,
                getStatusClass,
                getStatusText,
                relatedOrderModalVisible,
                openRelatedOrderModal,
                searchSalesOrders,
                resetSalesOrderSearch,
                handleSalesOrderSelection,
                confirmSalesOrderSelection,
                formatDate,
                salesOrderList,
                isSalesOutbound,
                outboundTotalQuantity,
                isRelateOutboundOrder,
                handleOutboundQuantityInput,
                handleCurrentOutStockQtyInput,
                warehouseOptions,
                operatorModalVisible,
                operatorDepartSearchKey,
                operatorManSearchKey,
                selectedOperatorList,
                filteredOperatorDepartData,
                filteredOperatorManData,
                handleOperatorDepartClick,
                filterOperatorDepartNode,
                addOperatorMan,
                removeOperatorMan,
                openOperatorModal,
                confirmOperatorSelection,
                consigneeOptions,
                loadConsigneeData,
                handleConsigneeChange,
                validateOutStockQuantity,
                handleWarehouseChange,
                handleOutboundTypeChange
            };
        }
    });

    app.use(ElementPlus);
    app.mount('#app');
</script>

<style>
    /* 保留原有样式并恢复附件相关样式 */
    .custom-active-action, .custom-inactive-action {
        color: red;
        font-size: 12px;
        font-weight: bold;
        width: 100%;
        text-align: center;
    }

    .input-error .el-input__inner {
        border-color: #f56c6c !important;
    }

    .el-switch__action {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .basicInfo, .stockInfo, .uploadAttachment {
        width: 82%;
        background-color: #fff;
        padding: 20px 0 10px;
        box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        margin: 20px;
    }

    .stockInfo, .uploadAttachment {
        padding-top: 10px;
        min-height: 400px;
    }
    /* 经办人选择模态框样式 */
    .selected-person-list {
        border: 1px solid #e5e7eb;
        border-radius: 4px;
        padding: 8px;
    }

    .selected-person-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px;
        border-bottom: 1px solid #f0f0f0;
    }

        .selected-person-item:last-child {
            border-bottom: none;
        }

    .person-info {
        display: flex;
        flex-direction: column;
    }

    .empty-tip {
        text-align: center;
        color: #909399;
        padding: 20px;
        font-size: 14px;
    }

    .tree-container {
        max-height: 400px;
        overflow-y: auto;
        margin-top: 10px;
    }

    .search-input {
        margin-bottom: 15px;
    }

    .saveBlock {
        display: grid;
        place-items: center;
        position: sticky;
        bottom: 0;
        width: 100%;
        height: 60px;
        background-color: #fff;
        z-index: 20;
        box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        margin: 20px;
    }

    .titleH {
        margin-left: 40px;
    }
    /* 添加合并货品的特殊样式 */
    .merged-goods-row {
        background-color: #f0f9ff !important;
    }

    .merged-location-tag {
        margin-bottom: 5px;
    }

    /* 合并货品的提示样式 */
    .merge-tooltip {
        font-size: 12px;
        color: #909399;
    }

    .form-row {
        display: flex;
        flex-wrap: wrap;
        margin: 0 -10px;
    }

    .form-col {
        flex: 0 0 50%;
        padding: 0 10px;
        box-sizing: border-box;
    }

    .full-width {
        flex: 0 0 100%;
    }

    .form-container {
        padding: 0 40px;
    }

    .required-label::before {
        content: '*';
        color: #F56C6C;
        margin-right: 4px;
    }

    .stockTable {
        margin: 20px 40px;
        width: 95%;
        overflow-x: auto;
    }

        .stockTable .el-table {
            width: 100%;
            table-layout: fixed;
        }

            .stockTable .el-table th {
                background-color: #f5f7fa;
                text-align: center;
            }

            .stockTable .el-table td {
                text-align: center;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }

    .add-remove-buttons {
        margin: 10px 40px;
    }



    .formTableInput, .formTableSelect {
        display: inline-block;
        width: 180px;
    }

    .related-order-input-group {
        display: flex;
        align-items: center;
    }
    /* 恢复附件上传样式 */
    .uploadAttach {
        padding-top: 30px;
        padding-left: 60px;
    }

    .promptWord {
        color: #606266;
    }

    .attachment-list {
        margin-top: 20px;
    }

    .attachment-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px;
        border: 1px solid #e5e7eb;
        border-radius: 4px;
        margin-bottom: 8px;
    }

    .attachment-info {
        display: flex;
        align-items: center;
    }

    .attachment-icon {
        margin-right: 8px;
        color: #409EFF;
    }

    /* 部门和人员选择模态框样式 */
    .tree-container {
        max-height: 400px;
        overflow-y: auto;
    }

    .valueV {
        color: orangered;
        font-weight: bolder;
    }

    .promptWord {
        color: #606266;
    }

    .status-tag {
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 12px;
    }

    .status-draft {
        background-color: #f0f0f0;
        color: #909399;
    }

    .status-pending {
        background-color: #e6f7ff;
        color: #1890ff;
    }

    .status-rejected {
        background-color: #fff2f0;
        color: #ff4d4f;
    }

    .status-normal {
        background-color: #f6ffed;
        color: #52c41a;
    }

    .status-disabled {
        background-color: #f5f5f5;
        color: #d9d9d9;
    }

    .total-summary {
        text-align: right;
        margin: 10px 40px;
        font-size: 16px;
        border-bottom: 1px solid #f0f0f0;
        height: 28px;
        padding: 10px 0px;
    }

    .search-input {
        margin-bottom: 15px;
    }

    .dialog-footer {
        text-align: right;
        padding: 10px 0;
    }

    /* 只读输入框样式 */
    .custom-readonly-input .el-input__inner {
        background-color: #f0f0f0 !important;
        cursor: pointer;
    }

    .custom-readonly-input .el-input__wrapper {
        background-color: #f0f0f0 !important;
    }

    /* 树控件样式优化 */
    .el-tree {
        border: 1px solid #e5e7eb;
        border-radius: 4px;
        padding: 10px;
    }

    .tree-title {
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #eee;
    }

    .basicInfo {
        width: 82%;
        background-color: #fff;
        padding: 20px 0 10px;
        box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        margin: 20px;
    }

    .titleH {
        margin-left: 40px;
    }

    .orderTable {
        margin: 0 auto;
        width: 80%;
        border-spacing: 0 40px;
    }

    .imp {
        color: red;
    }

    .orderTable tbody tr td {
        border-spacing: 0 20px;
    }

    .custom-readonly-input .el-input__inner {
        background-color: #f0f0f0 !important;
        padding: 0px;
    }

    .custom-readonly-input .el-input__wrapper {
        background-color: #f0f0f0 !important;
    }

    .related-order-input-group {
        display: flex;
        align-items: center;
    }

    .titleH {
        margin-left: 40px;
    }

    .orderTable {
        margin: 0 auto;
        width: 80%;
        border-spacing: 0 50px; /* 增加垂直间距 */
    }

    .imp {
        color: red;
    }

    .orderTable tbody tr td {
        border-spacing: 0 25px; /* 增加单元格间距 */
        padding: 12px 0; /* 增加上下内边距 */
        vertical-align: top; /* 顶部对齐 */
    }

    .custom-readonly-input .el-input__inner {
        background-color: #f0f0f0 !important;
        padding: 0px;
    }

    .custom-readonly-input .el-input__wrapper {
        background-color: #f0f0f0 !important;
    }

    .related-order-input-group {
        display: flex;
        align-items: center;
    }

    /* 为表格行添加更好的视觉分隔 */
    .orderTable tbody tr {
        height: 70px; /* 设置固定行高 */
    }

        /* 为备注行特殊处理 */
        .orderTable tbody tr:last-child td {
            padding-top: 20px; /* 备注行额外上边距 */
            padding-bottom: 20px; /* 备注行额外下边距 */
        }

    /* 调整表单元素间距 */
    .orderTable .el-input,
    .orderTable .el-select,
    .orderTable .el-cascader,
    .orderTable .el-date-picker {
        margin-bottom: 8px; /* 表单元素底部间距 */
    }

    /* 调整复选框位置 */
    .orderTable .el-checkbox {
        margin-top: 8px;
    }

    /* 调整文本域高度 */
    .orderTable .el-textarea .el-textarea__inner {
        min-height: 80px; /* 增加备注文本域高度 */
        resize: vertical; /* 允许垂直调整 */
    }

    /* 在 style 中添加 */
    .orderTable .el-date-picker {
        width: 160px !important; /* 强制固定宽度 */
        box-sizing: border-box; /* 确保内边距不影响总宽度 */
    }
</style>